package com.cloud.job.project.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cloud.common.core.asserts.ApiAssert;
import com.cloud.common.core.enums.ErrorCodeEnum;
import com.cloud.common.core.model.response.ApiResponses;
import com.cloud.common.core.model.supers.SuperController;
import com.cloud.common.security.annotation.PreAuth;
import com.cloud.job.project.model.entity.QuartzJob;
import com.cloud.job.project.service.IQuartzJobService;
import com.cloud.job.utils.CronUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Objects;

/**
 * <p>
 * 定时任务调度表 前端控制器
 * </p>
 *
 * @author Sam
 * @since 2021-02-08
 */
@Api(tags = {"定时任务调度"})
@RestController
@RequestMapping("/quartzJob")
public class QuartzJobRestController extends SuperController {

    @Autowired
    private IQuartzJobService quartzJobService;

    @PreAuth
    @ApiOperation("分页查询定时任务")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "jobName", value = "任务名称 模糊", paramType = "query"),
            @ApiImplicitParam(name = "jobGroup", value = "任务组名", paramType = "query"),
            @ApiImplicitParam(name = "invokeTarget", value = "调用目标字符串 模糊", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "状态（0正常 1暂停）", type = "int", paramType = "query"),
    })
    @GetMapping
    public ApiResponses<IPage<QuartzJob>> page(@ApiIgnore @ModelAttribute QuartzJob quartzJob) {
        IPage<QuartzJob> iPage = quartzJobService.page(this.getPage(), Wrappers.<QuartzJob>lambdaQuery()
                .like(StringUtils.isNotBlank(quartzJob.getJobName()), QuartzJob::getJobName, quartzJob.getJobName())
                .eq(StringUtils.isNotBlank(quartzJob.getJobGroup()), QuartzJob::getJobGroup, quartzJob.getJobGroup())
                .like(StringUtils.isNotBlank(quartzJob.getInvokeTarget()), QuartzJob::getInvokeTarget, quartzJob.getInvokeTarget())
                .eq(Objects.nonNull(quartzJob.getStatus()), QuartzJob::getStatus, quartzJob.getStatus()));
        return success(iPage);
    }

    @PreAuth
    @ApiOperation("单条查询定时任务")
    @GetMapping(value = "/{jobId}")
    public ApiResponses<QuartzJob> getInfo(@PathVariable("jobId") Long jobId) {
        return success(quartzJobService.getById(jobId));
    }

    @PreAuth
    @ApiOperation("新增定时任务")
    @PostMapping
    public ApiResponses<Void> create(@RequestBody QuartzJob quartzJob) throws SchedulerException {
        ApiAssert.isTrue(ErrorCodeEnum.INTERNAL_SERVER_ERROR.convert("cron表达式不正确"),
                CronUtils.isValid(quartzJob.getCronExpression()));
        quartzJobService.insertJob(quartzJob);
        return success();
    }

    @PreAuth
    @ApiOperation("修改定时任务")
    @PutMapping("/{jobId}")
    public ApiResponses<Void> updateById(@PathVariable("jobId") Long jobId, @RequestBody QuartzJob quartzJob) throws SchedulerException {
        quartzJob.setJobId(jobId);
        ApiAssert.isTrue(ErrorCodeEnum.INTERNAL_SERVER_ERROR.convert("cron表达式不正确"), CronUtils.isValid(quartzJob.getCronExpression()));
        quartzJobService.updateJob(quartzJob);
        return success();
    }

    @ApiOperation("定时任务状态修改")
    @PutMapping("/changeStatus")
    public ApiResponses<Void> changeStatus(@RequestBody QuartzJob job) throws SchedulerException {
        QuartzJob newJob = quartzJobService.getById(job.getJobId());
        newJob.setStatus(job.getStatus());
        quartzJobService.changeStatus(newJob);
        return success();
    }

    @PreAuth
    @ApiOperation("定时任务立即执行一次")
    @PutMapping("/run/{jobId}")
    public ApiResponses<Void> run(@PathVariable("jobId") Long jobId) throws SchedulerException {
        quartzJobService.run(jobId);
        return success();
    }

    @PreAuth
    @ApiOperation("删除定时任务")
    @DeleteMapping("/{jobIds}")
    public ApiResponses<Void> deleteByIds(@PathVariable Long[] jobIds) throws SchedulerException {
        quartzJobService.deleteJobByIds(jobIds);
        return success();
    }
}

